//
//  DHS2_SearchController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/6/4.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHS2_SearchController.h"
#import "DHS2_SearchHistoryCell.h"
#import "DHS2_SearchRecommendBrandsCell.h"
#import "DHS2_SearchRecommendBrandsItemCell.h"
#import "DHS2_SearchView.h"

@interface DHS2_SearchController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;
@property (weak, nonatomic) IBOutlet UIView *searchBgView;

@property (strong, nonatomic) DHS2_SearchView *searchContentView; //搜索视图

@property (strong, nonatomic) NSMutableArray *recommendBrandArr; //推荐品牌

@property (strong, nonatomic) NSMutableArray *histroyArr; //搜索记录

@end

@implementation DHS2_SearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchView.layer.cornerRadius = self.searchView.height / 2;
    
    CGFloat space = 0;
    if (iPhoneX) {
        space = 20;
    }
    self.searchContentView = [DHS2_SearchView shareDHS2_SearchView];
    [self.searchContentView setFrame:CGRectMake(0, self.tableView.top + space, kScreenWidth, self.view.height - self.tableView.top - space)];
    [self.searchContentView initView];
    self.searchContentView.type = @"全部";
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_SearchHistoryCell" bundle:nil] forCellReuseIdentifier:kDHS2_SearchHistoryCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_SearchRecommendBrandsCell" bundle:nil] forCellReuseIdentifier:kDHS2_SearchRecommendBrandsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_SearchRecommendBrandsItemCell" bundle:nil] forCellReuseIdentifier:kDHS2_SearchRecommendBrandsItemCell];
    
    self.searchTF.delegate = self;
    [self.searchBgView bk_whenTapped:^{
        self.searchBgView.hidden = YES;
        [self.searchTF resignFirstResponder];
    }];
    
    NSArray *history = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SEARCH_HISTORY];
    if (history.count > 0) {
        [self.histroyArr addObjectsFromArray:history];
    }
    
    [self loadRecommendBrand];
}

- (NSMutableArray *)recommendBrandArr{
    if (!_recommendBrandArr) {
        _recommendBrandArr = [NSMutableArray array];
    }
    return _recommendBrandArr;
}

- (NSMutableArray *)histroyArr{
    if (!_histroyArr) {
        _histroyArr = [NSMutableArray array];
    }
    return _histroyArr;
}

- (void)loadRecommendBrand{
    [self.recommendBrandArr removeAllObjects];
    [[DHNetAPIClient shareDHNetAPIClient] request_brands_recommendsWithParams:@{} andBlock:^(id data, NSError *error) {
        NSArray *temp = [data objectForKey:@"recommends"];
        for (NSDictionary *product in temp) {
            NSArray *items = [product objectForKey:@"products"];
            if (items.count > 0) {
                [self.recommendBrandArr addObject:product];
            }
        }
        
        [self.tableView reloadData];
    }];
}

- (IBAction)backClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"clear_history"]) {
        [self.histroyArr removeAllObjects];
        [self.tableView reloadData];
    }else if ([eventName isEqualToString:@"history_keyword_click"]){
        [self.searchTF resignFirstResponder];
        [self.view addSubview:self.searchContentView];
        [self.searchContentView searchAction:[userInfo objectForKey:@"key"]];
        self.searchBgView.hidden = YES;
        self.searchTF.text = [userInfo objectForKey:@"key"];
    }
}

#pragma mark - UITableViewDataSource and UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.histroyArr.count > 0) {
        return 2 + self.recommendBrandArr.count;
    }else{
        return 1 + self.recommendBrandArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.histroyArr.count > 0) {
        if (indexPath.row == 0) {
            return 140;
        }else if (indexPath.row == 1){
            return 50;
        }else{
            NSDictionary *dic = [self.recommendBrandArr objectAtIndex:indexPath.row - 2];
            NSArray *arr = [dic objectForKey:@"products"];
            if (arr.count % 2 ==0) {
                return 78 + (arr.count / 2) * 280;
            }else{
                return 78 + (arr.count / 2 + 1) * 280;
            }
        }
    }else{
        if (indexPath.row == 0) {
            return 50;
        }else{
            NSDictionary *dic = dic = [self.recommendBrandArr objectAtIndex:indexPath.row - 1];;
            NSArray *arr = [dic objectForKey:@"products"];
            if (arr.count % 2 ==0) {
                return 78 + (arr.count / 2) * 280;
            }else{
                return 78 + (arr.count / 2 + 1) * 280;
            }
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.histroyArr.count > 0) {
        if (indexPath.row == 0) {
            DHS2_SearchHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_SearchHistoryCell forIndexPath:indexPath];
            if (self.histroyArr.count > 0) {
                cell.historyView.arr = self.histroyArr;
            }else{
                cell.historyView.arr = @[];
                [cell.historyView removeAllSubviews];
            }
            return cell;
        }else if (indexPath.row == 1){
            DHS2_SearchRecommendBrandsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_SearchRecommendBrandsCell forIndexPath:indexPath];
            return cell;
        }else{
            DHS2_SearchRecommendBrandsItemCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_SearchRecommendBrandsItemCell forIndexPath:indexPath];
            NSDictionary *dic = [self.recommendBrandArr objectAtIndex:indexPath.row - 2];
            [cell updateCell:dic];
            return cell;
        }
    }else{
        if (indexPath.row == 0){
            DHS2_SearchRecommendBrandsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_SearchRecommendBrandsCell forIndexPath:indexPath];
            return cell;
        }else{
            DHS2_SearchRecommendBrandsItemCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_SearchRecommendBrandsItemCell forIndexPath:indexPath];
            NSDictionary *dic = [self.recommendBrandArr objectAtIndex:indexPath.row - 1];
            [cell updateCell:dic];
            return cell;
        }
    }
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"%@",textField.text);
    if (textField.text.length > 0) {
        [textField resignFirstResponder];
        [self.view addSubview:self.searchContentView];
        [self.searchContentView searchAction:textField.text];
        self.searchBgView.hidden = YES;
        
        if (![self.histroyArr containsObject:textField.text]) {
            if (self.histroyArr.count >= 10) {
                [self.histroyArr replaceObjectAtIndex:0 withObject:textField.text];
            }else{
                [self.histroyArr addObject:textField.text];
            }
        }
        
        [[NSUserDefaults standardUserDefaults] setObject:self.histroyArr forKey:USER_SEARCH_HISTORY];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        [NSObject showHudTipStr:@"请输入搜索关键字"];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.searchBgView.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
